﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Kinect;
using Microsoft.Speech;
using Microsoft.Speech.AudioFormat;
using Microsoft.Speech.Recognition;
using System.IO;
using System.Diagnostics;
using Coding4Fun.Kinect.Wpf;
using Coding4Fun.Kinect.Wpf.Controls;
using System.Threading;

namespace Oprah
{
    /// <summary>
    /// Interaction logic for Game.xaml
    /// </summary>
    public partial class MainGame : Window
    {
        private readonly WriteableBitmap bitmapWave;
        private readonly byte[] pixels;
        private readonly double[] energyBuffer = new double[WaveImageWidth];
        private readonly byte[] blackPixels = new byte[WaveImageWidth * WaveImageHeight];
        private readonly Int32Rect fullImageRect = new Int32Rect(0, 0, WaveImageWidth, WaveImageHeight);
        private const double AngleChangeSmoothingFactor = 0.35;
        private const int WaveImageWidth = 500;
        private const int WaveImageHeight = 100;
        private KinectSensor kinect;
        private double angle;
        private bool running = true;
        private DispatcherTimer readyTimer;
        private EnergyCalculatingPassThroughStream stream;
        private SpeechRecognitionEngine speechRecognizer;
        private String word;
        private Queue<string> question = new Queue<string>();
        private int readScore;
        private int spellScore;
        private int questionNum;
        private int totalScore;
        private double percentage;
        private bool readCorrect = false;
        private bool spellCorrect = false;
        private int starScore;
        private int spellTries = 1;
        private int readTries = 1;
        private bool isChecked = false;
        Random rand = new Random();
        ArrayList LetterList = new ArrayList();
        ArrayList RandomLetter = new ArrayList();
        string[] Alphabets = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
             
        bool closing = false;
        const int skeletonCount = 6;
        Skeleton[] allSkeletons = new Skeleton[skeletonCount];

        private static double _topBoundary;
        private static double _bottomBoundary;
        private static double _leftBoundary;
        private static double _rightBoundary;
        private static double _itemLeft;
        private static double _itemTop;


        public MainGame()
        {
            InitializeComponent();
            WB.init();
            var colorList = new List<Color> { Colors.Black, Colors.Green };
            this.bitmapWave = new WriteableBitmap(WaveImageWidth, WaveImageHeight, 96, 96, PixelFormats.Indexed1, new BitmapPalette(colorList));

            this.pixels = new byte[WaveImageWidth];
            for (int i = 0; i < this.pixels.Length; i++)
            {
                this.pixels[i] = 0xff;
            }

            HideComponents();
            
            SensorChooser.KinectSensorChanged += this.SensorChooserKinectSensorChanged;
            //hb1.Click += new RoutedEventHandler(hb1_Click);
            //hb2.Click += new RoutedEventHandler(hb2_Click);
            //hb3.Click += new RoutedEventHandler(hb3_Click);
            //hb4.Click += new RoutedEventHandler(hb4_Click);
            //hb5.Click += new RoutedEventHandler(hb5_Click);
            //hb6.Click += new RoutedEventHandler(hb6_Click);
            //hbdelete.Click += new RoutedEventHandler(hbdelete_Click);
            //hbenter.Click += new RoutedEventHandler(hbenter_Click);

            //question.Enqueue("jam");
            //enqueue the questions
            ////question.Enqueue("cat");
            ////question.Enqueue("mat");
            //question.Enqueue("pan");
            //question.Enqueue("nap");
            ////question.Enqueue("can");
            //question.Enqueue("tan");
            ////question.Enqueue("ham");

            question.Enqueue("sun");
            
            //question.Enqueue("pat");
            //question.Enqueue("jab");
            //question.Enqueue("sad");
            //question.Enqueue("lad");
            //question.Enqueue("lap");

            //question.Enqueue("map");
           
            //question.Enqueue("vat");
            //question.Enqueue("bad");
            //question.Enqueue("fad");
            //question.Enqueue("sag");
            //question.Enqueue("sat");
            //question.Enqueue("rat");
            //question.Enqueue("fan");
            //question.Enqueue("wax");
            //question.Enqueue("van");
            //question.Enqueue("hat");
            //question.Enqueue("sap");
            //question.Enqueue("tap");
            //question.Enqueue("had");
            //question.Enqueue("mad");
            //question.Enqueue("ran");
            //question.Enqueue("cap");
            //question.Enqueue("man");
            //question.Enqueue("cab");
            //question.Enqueue("nab");
            //question.Enqueue("pad");
            //question.Enqueue("bag");
            
            //question.Enqueue("wag");
            question.Enqueue("fat");

            //QueueWord();
            
        }

        private static RecognizerInfo GetKinectRecognizer()
        {
            Func<RecognizerInfo, bool> matchingFunc = r =>
            {
                string value;
                r.AdditionalInfo.TryGetValue("Kinect", out value);
                return "True".Equals(value, StringComparison.InvariantCultureIgnoreCase) && "en-US".Equals(r.Culture.Name, StringComparison.InvariantCultureIgnoreCase);
            };
            return SpeechRecognitionEngine.InstalledRecognizers().Where(matchingFunc).FirstOrDefault();
        }

        private void SensorChooserKinectSensorChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            KinectSensor oldSensor = e.OldValue as KinectSensor;
            if (oldSensor != null)
            {
                this.UninitializeKinect();
            }

            KinectSensor newSensor = e.NewValue as KinectSensor;
            this.kinect = newSensor;

            if (newSensor != null)
            {
                //this.InitializeKinect();
                this.InitializeFingers();
            }
        }

        private void InitializeFingers()
        {

            var sensor = this.kinect;          

            var parameters = new TransformSmoothParameters
            {
                Smoothing = 0.3f,
                Correction = 0.0f,
                Prediction = 0.0f,
                JitterRadius = 1.0f,
                MaxDeviationRadius = 0.5f
            };

            sensor.SkeletonStream.Enable(parameters);

            sensor.SkeletonStream.Enable();

            sensor.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(sensor_AllFramesReady);
            sensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
            sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);

            try
            {
                sensor.Start();
            }
            catch (System.IO.IOException)
            {
                SensorChooser.AppConflictOccurred();
            }
           
        }
        #region kinectbuttons

        void sensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
        {
            if (closing)
            {
                return;
            }

            Skeleton first = GetFirstSkeleton(e);

            if (first == null)
            {
                return;
            }
            
            ScalePosition(imgCursor, first.Joints[JointType.HandRight]);

            GetCameraPoint(first, e);
        }

        Skeleton GetFirstSkeleton(AllFramesReadyEventArgs e)
        {
            using (SkeletonFrame skeletonFrameData = e.OpenSkeletonFrame())
            {
                if (skeletonFrameData == null)
                {
                    return null;
                }


                skeletonFrameData.CopySkeletonDataTo(allSkeletons);

                
                Skeleton first = (from s in allSkeletons
                                  where s.TrackingState == SkeletonTrackingState.Tracked
                                  select s).FirstOrDefault();

                return first;

            }
        }

        void GetCameraPoint(Skeleton first, AllFramesReadyEventArgs e)
        {

            using (DepthImageFrame depth = e.OpenDepthImageFrame())
            {
                if (depth == null || SensorChooser.Kinect == null)
                {
                    return;
                }

                DepthImagePoint rightDepthPoint =
                    depth.MapFromSkeletonPoint(first.Joints[JointType.HandRight].Position);

                //ColorImagePoint rightColorPoint =
                //    depth.MapToColorImagePoint(rightDepthPoint.X, rightDepthPoint.Y,
                //    ColorImageFormat.RgbResolution640x480Fps30);


                //Set location
                //CameraPosition(rightEllipse, rightColorPoint);

                CheckButton(hb1, imgCursor);
                CheckButton(hb2, imgCursor);
                CheckButton(hb3, imgCursor);
                CheckButton(hb4, imgCursor);
                CheckButton(hb5, imgCursor);
                CheckButton(hb6, imgCursor);
                CheckButton(hbdelete, imgCursor);
                CheckButton(hbenter, imgCursor);
                CheckButton(hbSave, imgCursor);
            }
        }

        private void CheckButton(HoverButton button, Image image)
        {
            if (IsItemMidpointInContainer(button, image))
            {
                button.Hovering();
            }
            else
            {
                button.Release();

            }
        }

        public bool IsItemMidpointInContainer(FrameworkElement container, FrameworkElement target)
        {
            FindValues(container, target);

            if (_itemTop < _topBoundary || _bottomBoundary < _itemTop)
            {
                //Midpoint of target is outside of top or bottom
                return false;
            }

            if (_itemLeft < _leftBoundary || _rightBoundary < _itemLeft)
            {
                //Midpoint of target is outside of left or right
                return false;
            }

            return true;
        }

        private void FindValues(FrameworkElement container, FrameworkElement target)
        {

            if (closing)
            {
                return;
            }
            try
            {
                var containerTopLeft = container.PointToScreen(new Point());
                var itemTopLeft = target.PointToScreen(new Point());

                _topBoundary = containerTopLeft.Y;
                _bottomBoundary = _topBoundary + container.ActualHeight;
                _leftBoundary = containerTopLeft.X;
                _rightBoundary = _leftBoundary + container.ActualWidth;

                //use midpoint of item (width or height divided by 2)
                _itemLeft = itemTopLeft.X + (target.ActualWidth / 2);
                _itemTop = itemTopLeft.Y + (target.ActualHeight / 2);
            }
            catch (Exception ex)
            { }
        }

        private void ScalePosition(FrameworkElement element, Joint joint)
        {
            //convert the value to X/Y
            //Joint scaledJoint = joint.ScaleTo(1280, 720); 

            //convert & scale (.3 = means 1/3 of joint distance)
            Joint scaledJoint = joint.ScaleTo(1280, 820, .3f, .3f);

            Canvas.SetLeft(element, scaledJoint.Position.X);
            Canvas.SetTop(element, scaledJoint.Position.Y);

        }
        #endregion

        #region iread
        private void InitializeKinect()
        {
            var sensor = this.kinect;
            this.speechRecognizer = this.CreateSpeechRecognizer();
            try
            {
                //sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
                sensor.Start();
                if (question.Count != 0)
                {
                    audioPlayer.Source = new Uri("C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/PleaseSayTheWord.mp3", UriKind.RelativeOrAbsolute);
                    audioPlayer.LoadedBehavior = MediaState.Play;
                    System.Threading.Thread.Sleep(1000);
                    audioPlayer.UnloadedBehavior = MediaState.Close;
                }
            }
            catch (Exception)
            {
                SensorChooser.AppConflictOccurred();
                return;
            }
        
            if (this.speechRecognizer != null && sensor != null)
            {
                // NOTE: Need to wait 2 seconds for device to be ready to stream audio right after initialization
                this.readyTimer = new DispatcherTimer();
                this.readyTimer.Tick += this.ReadyTimerTick;
                this.readyTimer.Interval = new TimeSpan(0, 0, 2);
                this.readyTimer.Start();
                //this.ReportSpeechStatus("Initializing audio stream...");
                this.UpdateInstructionsText(string.Empty);

                this.Closing += this.MainWindowClosing;
            }
        }

        private void ReadyTimerTick(object sender, EventArgs e)
        {
            try
            {
                this.Start();
                //this.ReportSpeechStatus("Ready to recognize speech!");
                //this.UpdateInstructionsText("Say the word below.");
                this.readyTimer.Stop();
                this.readyTimer = null;
            }
            catch (Exception ex)
            { }
        }

        private void UninitializeKinect()
        {
            var sensor = this.kinect;
            if (this.speechRecognizer != null && sensor != null)
            {
                sensor.AudioSource.Stop();
                //sensor.Stop();
                this.speechRecognizer.RecognizeAsyncCancel();
                this.speechRecognizer.RecognizeAsyncStop();
            }

            if (this.readyTimer != null)
            {
                this.readyTimer.Stop();
                this.readyTimer = null;
            }
        }

        private void MainWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.UninitializeKinect();
        }

        private SpeechRecognitionEngine CreateSpeechRecognizer()
        {
            RecognizerInfo ri = GetKinectRecognizer();
            if (ri == null)
            {
                MessageBox.Show(
                    @"There was a problem initializing Speech Recognition.
Ensure you have the Microsoft Speech SDK installed.",
                    "Failed to load Speech SDK",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                this.Close();
                return null;
            }

            SpeechRecognitionEngine sre;
            try
            {
                sre = new SpeechRecognitionEngine(ri.Id);
            }
            catch
            {
                MessageBox.Show(
                    @"There was a problem initializing Speech Recognition.
Ensure you have the Microsoft Speech SDK installed and configured.",
                    "Failed to load Speech SDK",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                this.Close();
                return null;
            }

            var grammar = new Choices();

            word = question.Dequeue();

            grammar.Add(word);
            
            var gb = new GrammarBuilder { Culture = ri.Culture };

            System.Diagnostics.Debug.WriteLine(ri.Culture.DisplayName);

            gb.Append(grammar);

            // Create the actual Grammar instance, and then load it into the speech recognizer.
            var g = new Grammar(gb);

            sre.LoadGrammar(g);
            sre.SpeechRecognized += this.SreSpeechRecognized;
            //sre.SpeechRecognitionRejected += this.SreSpeechRecognitionRejected;

            SetImage();
            questionNum += 1;
            return sre;
           
            
        }

        //Checking if word said is vaild or invaild
        private void SreSpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            if (rotTx.Angle > -20 && rotTx.Angle < 20)
            {
                if (e.Result.Confidence > 0.8 && e.Result.Text.ToString() == word)
                {
                    //string status = "You got it correct!";
                    audioPlayer.Source = new Uri("C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/NiceJob.mp3", UriKind.RelativeOrAbsolute);
                    audioPlayer.LoadedBehavior = MediaState.Play;
                    System.Threading.Thread.Sleep(2500);
                    audioPlayer.UnloadedBehavior = MediaState.Close;
                    readCorrect = true;
                    //this.ReportSpeechStatus(status);
                    readScore = readScore + 10;
                    ShowComponents();
                    this.speechRecognizer.RecognizeAsyncCancel();
                }
                else
                {

                    if (readTries < 2)
                    {
                        //string status = "Nice try! Please try again! Tries: " + readTries;
                        //this.ReportSpeechStatus(status) ;
                        readTries += 1;
                        this.speechRecognizer.RecognizeAsyncStop();
                        audioPlayer.Source = new Uri("C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/TryAgain.mp3", UriKind.RelativeOrAbsolute);
                        audioPlayer.LoadedBehavior = MediaState.Play;
                        System.Threading.Thread.Sleep(1500);
                        correctionForVoice();
                        audioPlayer.UnloadedBehavior = MediaState.Close;

                        this.speechRecognizer.RecognizeAsync();
                        //this.speechRecognizer.RecognizeAsync();
                        //
                    }
                    else
                    {
                        audioPlayer.Source = new Uri("C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/GoodEffort.mp3", UriKind.RelativeOrAbsolute);
                        audioPlayer.LoadedBehavior = MediaState.Play;
                        System.Threading.Thread.Sleep(1500);
                        audioPlayer.UnloadedBehavior = MediaState.Close;
                        //string status = "Close enough but nice try!";
                        //this.ReportSpeechStatus(status);
                        readTries = 0;
                        readCorrect = false;
                        ShowComponents();
                        this.speechRecognizer.RecognizeAsyncStop();
                    }
                }
            }
            else
            {
                //this.RejectSpeech(e.Result);
                this.speechRecognizer.RecognizeAsyncStop();
                audioPlayer.Source = new Uri("C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/TryAgain.mp3", UriKind.RelativeOrAbsolute);
                audioPlayer.LoadedBehavior = MediaState.Play;
                System.Threading.Thread.Sleep(1500);
                audioPlayer.UnloadedBehavior = MediaState.Close;

                this.speechRecognizer.RecognizeAsync();
            }
        }
        

        private void ReportSpeechStatus(string status)
        {
            Dispatcher.BeginInvoke(new Action(() => { tbSpeechStatus.Text = status; }), DispatcherPriority.Normal);
        }

        private void UpdateInstructionsText(string instructions)
        {
            Dispatcher.BeginInvoke(new Action(() => { tbColor.Text = instructions; }), DispatcherPriority.Normal);
        }

        private void Start()
        {
            try
            {
                var audioSource = this.kinect.AudioSource;
                audioSource.BeamAngleMode = BeamAngleMode.Adaptive;
                var kinectStream = audioSource.Start();
                audioSource.EchoCancellationMode = EchoCancellationMode.CancellationAndSuppression;
                audioSource.AutomaticGainControlEnabled = false;
                this.stream = new EnergyCalculatingPassThroughStream(kinectStream);
                this.speechRecognizer.SetInputToAudioStream(
                this.stream, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
                this.speechRecognizer.RecognizeAsync(RecognizeMode.Single);
                var t = new Thread(this.PollSoundSourceLocalization);
                t.Start();
            }
            catch (Exception ex)
            { }
        }

        private void PollSoundSourceLocalization()
        {
            while (this.running)
            {
                var audioSource = this.kinect.AudioSource;
                if (audioSource.SoundSourceAngleConfidence > 0.2)
                {
                    // Smooth the change in angle
                    double a = AngleChangeSmoothingFactor * audioSource.SoundSourceAngleConfidence;
                    this.angle = ((1 - a) * this.angle) + (a * audioSource.SoundSourceAngle);

                    Dispatcher.BeginInvoke(new Action(() => { rotTx.Angle = -angle; }), DispatcherPriority.Normal);
                }

                Dispatcher.BeginInvoke(
                    new Action(
                        () =>
                        {
                            clipConf.Rect = new Rect(
                                0, 0, 100 + (600 * audioSource.SoundSourceAngleConfidence), 50);

                            stream.GetEnergy(energyBuffer);
                            this.bitmapWave.WritePixels(fullImageRect, blackPixels, WaveImageWidth, 0);

                            for (int i = 1; i < energyBuffer.Length; i++)
                            {
                                int energy = (int)(energyBuffer[i] * 5);
                                Int32Rect r = new Int32Rect(i, (WaveImageHeight / 2) - energy, 1, 2 * energy);
                                this.bitmapWave.WritePixels(r, pixels, 1, 0);
                            }
                        }),
                    DispatcherPriority.Normal);

                Thread.Sleep(50);
            }
        }

        private class EnergyCalculatingPassThroughStream : Stream
        {
            private const int SamplesPerPixel = 10;

            private readonly double[] energy = new double[WaveImageWidth];
            private readonly object syncRoot = new object();
            private readonly Stream baseStream;

            private int index;
            private int sampleCount;
            private double avgSample;

            public EnergyCalculatingPassThroughStream(Stream stream)
            {
                this.baseStream = stream;
            }

            public override long Length
            {
                get { return this.baseStream.Length; }
            }

            public override long Position
            {
                get { return this.baseStream.Position; }
                set { this.baseStream.Position = value; }
            }

            public override bool CanRead
            {
                get { return this.baseStream.CanRead; }
            }

            public override bool CanSeek
            {
                get { return this.baseStream.CanSeek; }
            }

            public override bool CanWrite
            {
                get { return this.baseStream.CanWrite; }
            }

            public override void Flush()
            {
                this.baseStream.Flush();
            }

            public void GetEnergy(double[] energyBuffer)
            {
                lock (this.syncRoot)
                {
                    int energyIndex = this.index;
                    for (int i = 0; i < this.energy.Length; i++)
                    {
                        energyBuffer[i] = this.energy[energyIndex];
                        energyIndex++;
                        if (energyIndex >= this.energy.Length)
                        {
                            energyIndex = 0;
                        }
                    }
                }
            }

            public override int Read(byte[] buffer, int offset, int count)
            {
                int retVal = this.baseStream.Read(buffer, offset, count);
                const double A = 0.3;
                lock (this.syncRoot)
                {
                    for (int i = 0; i < retVal; i += 2)
                    {
                        short sample = BitConverter.ToInt16(buffer, i + offset);
                        this.avgSample += sample * sample;
                        this.sampleCount++;

                        if (this.sampleCount == SamplesPerPixel)
                        {
                            this.avgSample /= SamplesPerPixel;

                            this.energy[this.index] = .2 + ((this.avgSample * 11) / (int.MaxValue / 2));
                            this.energy[this.index] = this.energy[this.index] > 10 ? 10 : this.energy[this.index];

                            if (this.index > 0)
                            {
                                this.energy[this.index] = (this.energy[this.index] * A) + ((1 - A) * this.energy[this.index - 1]);
                            }

                            this.index++;
                            if (this.index >= this.energy.Length)
                            {
                                this.index = 0;
                            }

                            this.avgSample = 0;
                            this.sampleCount = 0;
                        }
                    }
                }

                return retVal;
            }

            public override long Seek(long offset, SeekOrigin origin)
            {
                return this.baseStream.Seek(offset, origin);
            }

            public override void SetLength(long value)
            {
                this.baseStream.SetLength(value);
            }

            public override void Write(byte[] buffer, int offset, int count)
            {
                this.baseStream.Write(buffer, offset, count);
            }
        }
        #endregion


        private void hbenter_Click(object sender, RoutedEventArgs e)
        {
            isChecked = true;
            CheckAnswer();
            //totalScore = readScore + spellScore;
            //lblScore.Content = totalScore.ToString();

            //if (questionNum == 3)
            //{
            //    UninitializeKinect();
            //    var g = new Sky();
            //    this.Hide();
            //    g.Show();
            //    totalScore = readScore + spellScore;
            //    lblScore.Content = totalScore.ToString();
            //}

            skywrite();
            
        }

        private void skywrite()
        {
                UninitializeKinect();
                var g = new Sky(word);
                this.Hide();
                g.Show();
                totalScore = readScore + spellScore;
                lblScore.Content = totalScore.ToString();
        }

        private void hb1_Click(object sender, RoutedEventArgs e)
        {
            SetWord(hbl1);
        }

         private void hb2_Click(object sender, RoutedEventArgs e)
        {
            SetWord(hbl2);
        }

         private void hb3_Click(object sender, RoutedEventArgs e)
        {
            SetWord(hbl3);
        }

        private void hb4_Click(object sender, RoutedEventArgs e)
        {
            SetWord(hbl4);
        }

        private void hb5_Click(object sender, RoutedEventArgs e)
        {
            SetWord(hbl5);
        }

        private void hb6_Click(object sender, RoutedEventArgs e)
        {
            SetWord(hbl6);
        }

        private void hbdelete_Click(object sender, RoutedEventArgs e)
        {

            if (isChecked)
            {
                if ((lblLetter1.Content.ToString() != "") && (lblLetter2.Content.ToString() != "") && (lblLetter3.Content.ToString() != "") && (lblLetter3.Content.ToString() != word.ElementAt(2).ToString()))
                {
                    lblLetter3.Content = "";
                }
                //else
                //{
                    if ((lblLetter1.Content.ToString() != "") && (lblLetter2.Content.ToString() != "") && (lblLetter2.Content.ToString() != word.ElementAt(1).ToString()))
                    {
                        lblLetter2.Content = "";
                    }
                    //else
                    //{
                        if ((lblLetter1.Content.ToString() != "") && (lblLetter1.Content.ToString() != word.ElementAt(0).ToString()))
                        {
                            lblLetter1.Content = "";
                        }
                //    }
                //}
            }
            else 
            {
                if ((lblLetter1.Content.ToString() != "") && (lblLetter2.Content.ToString() != "") && (lblLetter3.Content.ToString() != ""))
                {
                    lblLetter3.Content = "";
                }
                if ((lblLetter1.Content.ToString() != "") && (lblLetter2.Content.ToString() != "") && (lblLetter3.Content.Equals("")))
                {
                    lblLetter2.Content = "";
                }
               if ((lblLetter1.Content.ToString() != "") && (lblLetter2.Content.Equals("")) && (lblLetter3.Content.Equals("")))
                {
                    lblLetter1.Content = "";
                }
            }
        }
            
        
        //Move on to next questions

        private void CheckWord()
        {
            InitializeKinect();

            //lblWord.Content = word;
            ClearLabel();
            isChecked = false;
            lblLetter1.Content = word.ElementAt(0);
            lblLetter2.Content = word.ElementAt(1);
            lblLetter3.Content = word.ElementAt(2);
            HideComponents();
            SetImage();
            spellTries = 1;
        }

        private void ShuffleLetters()
        {
            var shuffle = new Shuffler();
            shuffle.Shuffle(Alphabets);
           
            RandomLetter.Add(word.ElementAt(0));
            RandomLetter.Add(word.ElementAt(1));
            RandomLetter.Add(word.ElementAt(2));


            //while (RandomLetter.Count < 6)
            //{
            //    int i = rand.Next(1, 26);

            //    RandomLetter.Add(Alphabets[i]);
            //}

            //replacing as hardcode
            if (word == "dad")
            {
                RandomLetter.Add('b');
                RandomLetter.Add('e');
                RandomLetter.Add('m');
            }

            if (word == "jam")
            {
                RandomLetter.Add('i');
                RandomLetter.Add('o');
                RandomLetter.Add('n');
            }

            if (word == "map")
            {
                RandomLetter.Add('q');
                RandomLetter.Add('o');
                RandomLetter.Add('n');
            }

            shuffle.ShuffleArrayList(RandomLetter);

           }

        //playing the correct sound for the word
        private void correctionForVoice()
        {
            //tbSpeechStatus.Text = "Hint!";
            audioPlayer.Source = new Uri("C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/" + word + ".mp3", UriKind.RelativeOrAbsolute);
            audioPlayer.LoadedBehavior = MediaState.Play;
            System.Threading.Thread.Sleep(1500);
        }

        private void ShowComponents()
        {
            
            hbl1.Visibility = Visibility.Visible;
            hbl2.Visibility = Visibility.Visible;
            hbl3.Visibility = Visibility.Visible;
            hbl4.Visibility = Visibility.Visible;
            hbl5.Visibility = Visibility.Visible;
            hbl6.Visibility = Visibility.Visible;
            hbdelete.Visibility = Visibility.Visible;
            hbenter.Visibility = Visibility.Visible;
            hb1.Visibility = Visibility.Visible;
            hb2.Visibility = Visibility.Visible;
            hb3.Visibility = Visibility.Visible;
            hb4.Visibility = Visibility.Visible;
            hb5.Visibility = Visibility.Visible;
            hb6.Visibility = Visibility.Visible;
            hb1.IsEnabled = true;
            hb2.IsEnabled = true;
            hb3.IsEnabled = true;
            hb4.IsEnabled = true;
            hb5.IsEnabled = true;
            hb6.IsEnabled = true;
            hbdelete.IsEnabled = true;
            hbenter.IsEnabled = true;
            lblLetter1.Content = "";
            lblLetter2.Content = "";
            lblLetter3.Content = "";
            SetRandomLetters();

            //var p1 = new System.Windows.Media.MediaPlayer();
            //p1.Open(new System.Uri(@"C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/ArrangeTheWord.mp3"));
            //p1.Play();

            //System.Threading.Thread.Sleep(3000);

            //var p2 = new System.Windows.Media.MediaPlayer();
            //p2.Open(new System.Uri(@"C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/mad.wma"));
            //p2.Play();

            audioPlayer.Source = new Uri("C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/ArrangeTheWord.mp3", UriKind.RelativeOrAbsolute);
            audioPlayer.LoadedBehavior = MediaState.Play;

            System.Threading.Thread.Sleep(3000);

            audioPlayer.Source = new Uri("C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/"+ word +".mp3", UriKind.RelativeOrAbsolute);
            audioPlayer.LoadedBehavior = MediaState.Play;
            audioPlayer.UnloadedBehavior = MediaState.Close;

        }

        private void HideComponents()
        {
            hbl1.Visibility = Visibility.Hidden;
            hbl2.Visibility = Visibility.Hidden;
            hbl3.Visibility = Visibility.Hidden;
            hbl4.Visibility = Visibility.Hidden;
            hbl5.Visibility = Visibility.Hidden;
            hbl6.Visibility = Visibility.Hidden;
            hbdelete.Visibility = Visibility.Hidden;
            hbenter.Visibility = Visibility.Hidden;
            hb1.Visibility = Visibility.Hidden;
            hb2.Visibility = Visibility.Hidden;
            hb3.Visibility = Visibility.Hidden;
            hb4.Visibility = Visibility.Hidden;
            hb5.Visibility = Visibility.Hidden;
            hb6.Visibility = Visibility.Hidden;
            hb1.IsEnabled = false;
            hb2.IsEnabled = false;
            hb3.IsEnabled = false;
            hb4.IsEnabled = false;
            hb5.IsEnabled = false;
            hb6.IsEnabled = false;
            hbdelete.IsEnabled = false;
            hbenter.IsEnabled = false;

        }

        private void ClearLabel()
        {
            imgt1.Source = new BitmapImage(new Uri("/images/TxtAre.png", UriKind.RelativeOrAbsolute));
            imgt2.Source = new BitmapImage(new Uri("/images/TxtAre.png", UriKind.RelativeOrAbsolute));
            imgt3.Source = new BitmapImage(new Uri("/images/TxtAre.png", UriKind.RelativeOrAbsolute));
            imgTxt1.Source = new BitmapImage(new Uri("/images/TxtArea.png", UriKind.RelativeOrAbsolute));
            imgTxt2.Source = new BitmapImage(new Uri("/images/TxtArea.png", UriKind.RelativeOrAbsolute));
            imgTxt3.Source = new BitmapImage(new Uri("/images/TxtArea.png", UriKind.RelativeOrAbsolute));
        }

        private void SetRandomLetters()
        {
            ShuffleLetters();
            hbl1.Content = RandomLetter[0].ToString();
            hbl2.Content = RandomLetter[1].ToString();
            hbl3.Content = RandomLetter[2].ToString();
            hbl4.Content = RandomLetter[3].ToString();
            hbl5.Content = RandomLetter[4].ToString();
            hbl6.Content = RandomLetter[5].ToString();
            RandomLetter.Clear();

        }

        private void CheckAnswer()
        {
            string ans = lblLetter1.Content.ToString() + lblLetter2.Content.ToString() + lblLetter3.Content.ToString();

            if (ans == word)
            {
                spellScore += 10;
                if (spellTries == 1)
                {
                    spellCorrect = true;
                }
                if (readCorrect == true && spellCorrect == true)
                {
                    starScore += 1;
                }
                CheckWord();
            }
            else
            {
                if (lblLetter1.Content.ToString() != word.ElementAt(0).ToString())
                {
                    imgTxt1.Source = new BitmapImage(new Uri("/images/wrong.png", UriKind.RelativeOrAbsolute));
                }
                if (lblLetter2.Content.ToString() != word.ElementAt(1).ToString())
                {
                    imgTxt2.Source = new BitmapImage(new Uri("/images/wrong.png", UriKind.RelativeOrAbsolute));
                }
                if (lblLetter3.Content.ToString() != word.ElementAt(2).ToString())
                {
                    imgTxt3.Source = new BitmapImage(new Uri("/images/wrong.png", UriKind.RelativeOrAbsolute));
                }
                if (lblLetter1.Content.ToString() == word.ElementAt(0).ToString())
                {
                    imgt1.Source = new BitmapImage(new Uri("/images/tick.png", UriKind.RelativeOrAbsolute));
                }
                if (lblLetter2.Content.ToString() == word.ElementAt(1).ToString())
                {
                    imgt2.Source = new BitmapImage(new Uri("/images/tick.png", UriKind.RelativeOrAbsolute));
                }
                if (lblLetter3.Content.ToString() == word.ElementAt(2).ToString())
                {
                    imgt3.Source = new BitmapImage(new Uri("/images/tick.png", UriKind.RelativeOrAbsolute));
                }
                spellTries += 1;
                spellCorrect = false;
            }

        }

        private void SetImage()
        {
            //string path = "";
            foreach (WB wb in WB.wordbank)
            {
                if (word == wb.word)
                {
                    imgPicture.Source = new BitmapImage(new Uri(wb.path, UriKind.RelativeOrAbsolute));
                    break;
                }
            }
            SetStar();

        }

        private void SetWord(Label lbl)
        {
            try
            {
                if (lblLetter1.Content.ToString().Equals(""))
                {
                    lblLetter1.Content = lbl.Content.ToString();
                    
                }
                else if ((lblLetter1.Content != "") && lblLetter2.Content.ToString().Equals(""))
                {
                    lblLetter2.Content = lbl.Content.ToString();
                }
                else if ((lblLetter1.Content != "") && (lblLetter2.Content != "") && (lblLetter3.Content.ToString().Equals("")))
                {
                    lblLetter3.Content = lbl.Content.ToString();
                }

            }
            catch (Exception ex)
            {
            }
        }

        private void SetStar()
        {
            if (starScore == 1)
            {
                star1.Source = new BitmapImage(new Uri("/images/Star.png", UriKind.RelativeOrAbsolute));
            }
            if (starScore == 2)
            {
                star2.Source = new BitmapImage(new Uri("/images/Star.png", UriKind.RelativeOrAbsolute));
            }
            if (starScore == 3)
            {
                star3.Source = new BitmapImage(new Uri("/images/Star.png", UriKind.RelativeOrAbsolute));
            }
            if (starScore == 4)
            {
                star4.Source = new BitmapImage(new Uri("/images/Star.png", UriKind.RelativeOrAbsolute));
            }
        }

        private void hbSave_Click(object sender, RoutedEventArgs e)
        {
            audioPlayer.Source = new Uri("C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/Saving.mp3", UriKind.RelativeOrAbsolute);
            audioPlayer.LoadedBehavior = MediaState.Play;
            audioPlayer.UnloadedBehavior = MediaState.Close;
            var g = new GamePage();
            this.Hide();
            g.Show();
            g.labelTS.Content = totalScore.ToString();
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F1)
            {
                //this.InitializeKinect();
                CheckWord();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //var p1 = new System.Windows.Media.MediaPlayer();
            //p1.Open(new System.Uri(@"C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/Welcome.mp3"));
            //p1.Play();

            audioPlayer.Source = new Uri("C:/Users/student/Documents/Visual Studio 2010/Projects/Hitler/Audio/Welcome.mp3", UriKind.RelativeOrAbsolute);
            audioPlayer.LoadedBehavior = MediaState.Play;
            audioPlayer.UnloadedBehavior = MediaState.Close;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            var d = new GamePage();
            this.Hide();
            d.Show();
        }

        private void StartInit()
        {
        }

        private void QueueWord()
        {
            ArrayList qw = new ArrayList();
            foreach (WB w in WB.wordbank)
            {
                qw.Add(w.word);
            }

            var shuffle = new Shuffler();
            shuffle.ShuffleArrayList(qw);

            foreach (string w in qw)
            {
                question.Enqueue(w);
            }
        }
        
    }
}
